const routerMap = {
  "Layout": () => import("@/views/layout/Layout"),
  "eleTable": () => import("@/views/demoPage/children/eleTable.vue"),
  "editTable": () => import("@/views/demoPage/children/editTable.vue")
};

const menu = {
  state: {
    items: []
  },
  mutations: {
    ADD_MENU: (state, menuItems) => {
      if (menuItems.length == 0) {
        state.items = [];
      } else {
        state.items = menuItems;
      }
    }
  },
  actions: {
    addMenu: ({ commit }, menuItems) => {
      let menu = generateRoutesFromMenu(menuItems);
      commit("ADD_MENU", menu);
    }
  }
};

function generateRoutesFromMenu(menu = []) {
  let asyncMenu = [];
  menu.map((item, idx) => {
    let menus = {};
    menus.path = item.path;
    menus.component = routerMap[item.component];
    menus.redirect = item.redirect;
    menus.name = item.name;
    menus.meta = item.meta;
    menus.children = transferChildren(item.children);
    asyncMenu.push(menus);
  })
  return asyncMenu;
}

function transferChildren(childrenArr) {
  let childMenu = [];
  childrenArr.map((cur, index) => {
    let cdm = {};
    cdm.path = cur.path;
    cdm.name = cur.name;
    cdm.component = routerMap[cur.component];
    cdm.meta = cur.meta;
    if (cur.children && cur.children.length > 0) {
      cdm.children = transferChildren(cur.children);
    }
    childMenu.push(cdm);
  });
  return childMenu;
}

export default menu;
